/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package users;

import avenue.Session;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import model.AppUser;
import model.RolePermission;

/**
 *
 * @author chrysa
 */
public class UsersList extends javax.swing.JInternalFrame {
    
    public UsersList() {
        em = Session.emf.createEntityManager();
        em.getTransaction().begin();
        initComponents();
        RolePermission rp = Session.GetPermission(Session.USERS_MODULE);
        this.NewUser.setEnabled(rp.getCanCreate());
        this.EditUser.setEnabled(rp.getCanUpdate());
        this.DeleteUser.setEnabled(rp.getCanDelete());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        query1 = em.createQuery("select au from AppUser au");
        appUserList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query1.getResultList());
        NewUser = new javax.swing.JButton();
        DeleteUser = new javax.swing.JButton();
        EditUser = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        appUsersTable = new javax.swing.JTable();

        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Χρήστες");

        NewUser.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        NewUser.setText("Νέος");
        NewUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NewUserActionPerformed(evt);
            }
        });

        DeleteUser.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        DeleteUser.setText("Διαγραφή");
        DeleteUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteUserActionPerformed(evt);
            }
        });

        EditUser.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        EditUser.setText("Επεξεργασία");
        EditUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditUserActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Ακύρωση");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveButton.setText("Αποθήκευση");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        appUsersTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, appUserList, appUsersTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${LName}"));
        columnBinding.setColumnName("Επώνυμο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${FName}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${roleId}"));
        columnBinding.setColumnName("Ρόλος");
        columnBinding.setColumnClass(model.UserRole.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${stationId}"));
        columnBinding.setColumnName("Σταθμός");
        columnBinding.setColumnClass(model.Station.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${phone}"));
        columnBinding.setColumnName("Τηλέφωνο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${email}"));
        columnBinding.setColumnName("Email");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane2.setViewportView(appUsersTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(NewUser)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(DeleteUser)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(EditUser)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
                        .addComponent(cancelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(saveButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(NewUser)
                    .addComponent(DeleteUser)
                    .addComponent(EditUser)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void NewUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewUserActionPerformed
       AppUser u = new AppUser();
       em.persist(u);
       UserEdit euf = new UserEdit(null,true,u,em);
       euf.setTitle("Νέος Χρήστης");       
       euf.setVisible(true);
       if (euf.getReturnStatus() == UserEdit.RET_OK) {
           appUserList.add(u);           
       } else {
           em.remove(u);
       }
    }//GEN-LAST:event_NewUserActionPerformed

    private void DeleteUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteUserActionPerformed
        int s = appUsersTable.getSelectedRow();
        if (s >= 0) {
            AppUser u = appUserList.get(appUsersTable.convertRowIndexToModel(s));
            if (u.getId() != Session.getUser().getId()) {
                int choice = JOptionPane.showConfirmDialog(this,
                                          "Διαγραφή του χρήστη " + u.getUserName() + ";",
                                          "Επιβεβαίωση διαγραφής χρήστη",
                                          JOptionPane.YES_NO_OPTION);
                
                if (choice != 0) {
                    return;
                }
                
                appUserList.remove(u);
                em.remove(u);                
            } else { 
                JOptionPane.showMessageDialog(this, "Ο χρήστης " + u.getUserName() + " δεν μπορεί να διαγραφεί",
                                          "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_DeleteUserActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        try {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            this.dispose();
        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        try {
            if (em.getTransaction().isActive()) {
                em.getTransaction().commit();
            }
            this.dispose();
        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void EditUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditUserActionPerformed
        //Επελεγμένη γραμμή
        int s = appUsersTable.getSelectedRow();
        //αν έχει επιλεχθεί μια γραμμή
        if (s>=0) {
            AppUser u = appUserList.get(appUsersTable.convertRowIndexToModel(s));
            UserEdit euf = new UserEdit(null,true,u,em);
            euf.setTitle("Επεξεργασία Χρήστη: " + u.getUserName());
            euf.setVisible(true);
            if (euf.getReturnStatus() == UserEdit.RET_OK) {
                appUserList.set(s, u);           
            } else {
                em.refresh(u);
            }
        }
    }//GEN-LAST:event_EditUserActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton DeleteUser;
    private javax.swing.JButton EditUser;
    private javax.swing.JButton NewUser;
    private java.util.List<model.AppUser> appUserList;
    private javax.swing.JTable appUsersTable;
    private javax.swing.JButton cancelButton;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.persistence.Query query1;
    private javax.swing.JButton saveButton;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    private EntityManager em;
}
